package com.atguigu.yygh.oss.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.atguigu.yygh.oss.config.AliYunOssConfig;
import com.atguigu.yygh.oss.service.FileService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.Date;

/**
 * @author 孔德成
 * @slogan 致敬大师，致敬未来的你
 * @date 2021/9/11 12:01 下午
 * @desc
 */
@Slf4j
@Service
public class FileServiceImpl implements FileService {

    private final AliYunOssConfig aliYunOssConfig;

    public FileServiceImpl(AliYunOssConfig aliYunOssConfig) {
        this.aliYunOssConfig = aliYunOssConfig;
    }

    @Override
    public String upload(MultipartFile file) {
        // yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1（杭州）为例，Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
        String endpoint = aliYunOssConfig.getEndPoint();
        String accessKeyId = aliYunOssConfig.getAccessKeyID();
        String accessKeySecret = aliYunOssConfig.getAccessKeySecret();
        String bucketName = aliYunOssConfig.getBucketName();
        // 图片上传成功后的访问地址
        StringBuilder callUrl = new StringBuilder();
        callUrl.append("https://").append(bucketName).append(".").append(endpoint).append("/");
        try {
            // 1. 创建OSSClient实例
            OSS ossClient = new OSSClientBuilder().build("https://" + endpoint, accessKeyId, accessKeySecret);
            // 2. 获取文件流
            InputStream inputStream = file.getInputStream();
            // 3. 获取文件名
            String originalFilename = file.getOriginalFilename();
            assert originalFilename != null;
            String extName = originalFilename.substring(originalFilename.lastIndexOf("."));
            String fileName = IdUtil.simpleUUID() + extName;
            // 按照当前日期，创建文件夹，上传到创建文件夹里面
            String format = DateUtil.format(new Date(), "yyyy/MM/dd");
            String filePath = format + fileName;
            // 依次填写Bucket名称（例如examplebucket）和Object完整路径（例如exampledir/exampleobject.txt）。Object完整路径中不能包含Bucket名称。
            // 4. 上传文件
            ossClient.putObject(bucketName, filePath, inputStream);
            // 5. 关闭OSSClient。
            ossClient.shutdown();
            callUrl.append(filePath);
        } catch (IOException e) {
            e.printStackTrace();
        }
        log.info(callUrl.toString());
        return callUrl.toString();
    }

}
